<template>
  <div>
    <div class="card"
      style="margin-bottom: 10px;margin-right: 5px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <span style="color: #4a4d52">时间范围查询：</span><el-date-picker v-model="dateRange" value-format="YYYY-MM-DD"
        type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      <el-button style="margin-left: 10px" type="primary" @click="load">查询</el-button>
      <el-button type="info" style="margin: 0 10px" @click="reset">重置</el-button>
    </div>

    <div class="card"
      style="margin-bottom: 10px;margin-right: 5px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <el-table :data="data.tableData" stripe>
        <el-table-column label="编号" prop="endId"></el-table-column>
        <el-table-column label="记录号" prop="recordId"></el-table-column>
        <el-table-column label="终审结果" prop="reason">
          <template #default="scope">
            <el-tag :type="scope.row.reason == null ? 'success' : 'danger'">
              {{ scope.row.reason == null ? '通过' : '打回' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="终审操作时间" prop="createTime">
          <template #default="scope">
            <div class="ellipsis-text" :title="dateFormat(scope.row.createTime)">
              {{ dateFormat(scope.row.createTime) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="primary" @click="handleView(scope.row.recordId)">查看详细</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="card" style="margin-right: 5px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <el-pagination @current-change="load" @size-change="load" v-model:current-page="data.pageNum"
        v-model:page-size="data.pageSize" :page-sizes="[8, 13, 18, 23]" layout="total, sizes, prev, pager, next, jumper"
        :total="data.total" />
    </div>

    <el-dialog title="申请记录查看" width="50%" v-model="data.viewForm" :close-on-click-modal="false" destroy-on-close>
      <el-form :model="data.record" label-width="120px" ref="formRef">
        <el-descriptions column="1" border>
          <el-descriptions-item label="姓名">{{ data.record.stuName }}</el-descriptions-item>
          <el-descriptions-item label="创新创业活动类型">{{ data.record.typeName }}</el-descriptions-item>
          <el-descriptions-item label="创新创业活动项">{{ data.record.actName }}</el-descriptions-item>
          <el-descriptions-item label="材料申请时间">{{ dateFormat(data.record.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="申请材料">
            <el-button type="warning" @click="viewAppData(data.record.appData)">查看材料详细</el-button>
          </el-descriptions-item>
          <el-descriptions-item label="分配教师">{{ data.record.teaName }}</el-descriptions-item>
        </el-descriptions>
      </el-form>

      <template #footer>
        <el-button type="primary" @click="data.viewForm = false">关 闭</el-button>
      </template>
    </el-dialog>

    <el-dialog title="查看材料详细" v-model="data.appDataViewVisible" width="70%" destroy-on-close>
      <div style="padding: 20px; max-height: 60vh; overflow-y: auto;">
        <!-- 文件类型切换标签 -->
        <div style="margin-bottom: 15px; display: flex; flex-wrap: wrap;">
          <el-tag v-for="(file, index) in data.appDataList" :key="index"
            :type="data.activeFileIndex === index ? 'primary' : 'warning'" style="margin: 0 10px 10px 0; cursor: pointer;"
            @click="data.activeFileIndex = index">
            {{ getFileName(file.url) }} ({{ file.type }})
          </el-tag>
        </div>

        <!-- 图片预览 -->
        <div v-if="data.appDataList[data.activeFileIndex]?.type === 'image'"
          style="display: flex; justify-content: center;">
          <el-image :src="data.appDataList[data.activeFileIndex].url" fit="contain"
            style="max-width: 100%; max-height: 500px;" :preview-src-list="data.imagePreviewList">
            <template #placeholder>
              <div style="text-align: center; padding: 20px;">
                <el-icon class="is-loading" style="font-size: 24px;">
                  <Loading />
                </el-icon>
              </div>
            </template>
            <template #error>
              <div class="image-error">
                <el-icon>
                  <Picture />
                </el-icon>
                <p>图片加载失败</p>
              </div>
            </template>
          </el-image>
        </div>

        <!-- PDF预览 -->
        <div v-else-if="data.appDataList[data.activeFileIndex]?.type === 'pdf'" class="preview-container">
          <div ref="pdfContainer" style="width: 100%; height: 100%;"></div>
        </div>

        <!-- Word预览 -->
        <div v-else-if="data.appDataList[data.activeFileIndex]?.type === 'word'" class="preview-container">
          <div ref="wordContainer" style="width: 100%; height: 100%;"></div>
        </div>

        <!-- 其他文件类型 -->
        <div v-else-if="!['image', 'pdf', 'word'].includes(data.appDataList[data.activeFileIndex]?.type)"
          class="preview-container preview-error">
          <el-icon>
            <Files />
          </el-icon>
          <p>不支持在线预览</p>
          <el-button type="primary" @click="downloadFile(data.appDataList[data.activeFileIndex].url)">
            下载文件
          </el-button>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="data.appDataViewVisible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { nextTick, reactive, ref, watch } from "vue";
import alovaInstance from "@/utils/request";
import { ElMessage } from "element-plus";
import { dateFormat } from "@/utils/dateUtil";
import { renderAsync } from 'docx-preview';
import { checkEndRecord } from "@/api/college_admin/college";
import * as pdfjsLib from 'pdfjs-dist';
import 'pdfjs-dist/build/pdf.worker.entry';

const data = reactive({
  user: JSON.parse(localStorage.getItem('credit-system-user') || '{}'),
  pageNum: 1,
  pageSize: 8,
  total: 0,
  viewForm: false,
  form: {},
  tableData: [],
  record: {},
  status: '',
  grade: '',
  appDataViewVisible: false,
  // 新增：存储解析后的材料列表
  appDataList: [],
  activeFileIndex: 0,
  imagePreviewList: [],
  beginTime: '',
  endTime: '',
})

//日期范围
const dateRange = ref([])

const load = () => {
  console.log(dateRange.value)
  // 设置日期范围参数
  if (dateRange.value && dateRange.value.length === 2) {
    data.beginTime = dateRange.value[0];
    data.endTime = `${dateRange.value[1]} 23:59:59`;
  } else {
    data.beginTime = ''
    data.endTime = ''
  }
  alovaInstance.Get('/collegeAdmin/getRecord', {
    params: {
      adminId: data.user.adminId,
      page: data.pageNum,
      size: data.pageSize,
      beginTime: data.beginTime,
      endTime: data.endTime,
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list
      data.total = res.data?.total
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message);
  });
}

// 查看
const handleView = (row) => {
  data.form.recordId = row;
  checkEndRecord(data.form.recordId).then(res => {
    console.log(res);
    data.record = res.data
    console.log(data.record);

  }).catch(err => {
    ElMessage.error('操作失败：' + err.message);
  });
  data.viewForm = true
}

// 重置
const reset = () => {
  dateRange.value = []
  // 重置日期参数
  data.beginTime = ''
  data.endTime = ''
  //重新渲染数据
  load()
}

//文件类型映射
const fileTypeMap = {
  jpg: 'image',
  jpeg: 'image',
  png: 'image',
  gif: 'image',
  bmp: 'image',
  pdf: 'pdf',
  doc: 'word',
  docx: 'word'
};

// 在viewAppData方法中添加以下逻辑
const viewAppData = (appData) => {

  // 解析URL为数组
  const urlArray = appData.split(',');

  // 处理每个文件的类型
  data.appDataList = urlArray.map(url => {
    const extension = url.split('.').pop().toLowerCase();
    return {
      url,
      type: fileTypeMap[extension] || 'other',
      extension
    };
  });

  // 提取图片URL用于预览列表
  data.imagePreviewList = data.appDataList
      .filter(file => file.type === 'image')
      .map(file => file.url);
  // 默认激活第一个文件
  data.activeFileIndex = 0;
  // 打开对话框
  data.appDataViewVisible = true;
  // 等待DOM更新后渲染PDF/Word
  nextTick(() => {
    renderCurrentFile();
  });
};

// 添加文件渲染方法
const renderCurrentFile = () => {
  const file = data.appDataList[data.activeFileIndex];

  if (!file) return;

  // 清除之前渲染的内容
  if (pdfContainer.value) pdfContainer.value.innerHTML = '';
  if (wordContainer.value) wordContainer.value.innerHTML = '';

  switch (file.type) {
    case 'pdf':
      renderPDF(file.url);
      break;
    case 'word':
      renderWord(file.url);
      break;
  }
};

// 添加PDF渲染方法
const pdfContainer = ref(null);
const renderPDF = async (url) => {
  if (!pdfContainer.value) return;

  try {
    const loadingTask = pdfjsLib.getDocument(url);
    const pdf = await loadingTask.promise;

    // 清空容器
    pdfContainer.value.innerHTML = '';

    // 渲染第一页
    const page = await pdf.getPage(1);
    const viewport = page.getViewport({ scale: 1.5 });

    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    canvas.height = viewport.height;
    canvas.width = viewport.width;

    pdfContainer.value.appendChild(canvas);

    await page.render({
      canvasContext: context,
      viewport
    });
  } catch (error) {
    console.error('PDF渲染失败:', error);
    pdfContainer.value.innerHTML = '<p>PDF预览失败，请尝试下载查看</p>';
  }
};

// 添加Word渲染方法
const wordContainer = ref(null);
const renderWord = async (url) => {
  if (!wordContainer.value) return;
  try {
    // 获取Word文件
    const response = await fetch(url);
    const blob = await response.blob();
    // 给容器添加样式类
    wordContainer.value.className = 'word-preview-container';
    // 渲染Word文档
    await renderAsync(blob, wordContainer.value, null, {
      className: "docx", // 默认和文档样式类名
      inWrapper: true, // 启用包装器
      ignoreWidth: false,
      ignoreHeight: false,
      ignoreFonts: false,
      breakPages: true,
      debug: false,
      experimental: false,
      trimXmlDeclaration: true,
      useBase64URL: false,
      useMathMLPolyfill: false,
      showChanges: false,
    });
  } catch (error) {
    console.error('Word渲染失败:', error);
    wordContainer.value.innerHTML = '<p>Word预览失败，请尝试下载查看</p>';
  }
};

// 添加下载文件方法
const downloadFile = (url) => {
  const a = document.createElement('a');
  a.href = url;
  a.download = url.split('/').pop();
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
};

// 添加获取文件名方法
const getFileName = (url) => {
  const parts = url.split('/');
  return parts[parts.length - 1];
};

// 监听激活文件的变化
watch(() => data.activeFileIndex, () => {
  nextTick(renderCurrentFile);
});

load()

load()
</script>

<style lang="scss" scoped></style>